package com.situ.library.controller;

import com.situ.library.pojo.entity.Auth;
import com.situ.library.pojo.entity.User;
import com.situ.library.pojo.query.UserQuery;
import com.situ.library.service.IAuthService;
import com.situ.library.service.IUserService;
import com.situ.library.service.impl.AuthServiceImpl;
import com.situ.library.service.impl.UserServiceImpl;
import com.situ.library.util.*;
import org.springframework.util.ObjectUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@WebServlet("/user")
public class UserController extends BaseController {
    private IUserService userService = new UserServiceImpl();
    private IAuthService authService = new AuthServiceImpl();

    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String method = req.getParameter("method");
        switch (method){
            case "login":
                login(req, resp);
                break;
            case "logout":
                logout(req, resp);
                break;
            case "selectByPage":
                selectByPage(req, resp);
                break;
            case "deleteById":
                deleteById(req, resp);
                break;
            case "deleteAll":
                deleteAll(req, resp);
                break;
            case "add":
                add(req, resp);
                break;
            case "selectById":
                selectById(req, resp);
                break;
            case "update":
                update(req, resp);
                break;
        }
    }


    private void update(HttpServletRequest req, HttpServletResponse resp) {
        System.out.println("UserServlet.update");
        User user = MyBeanUtils.copyToBean(req, User.class);
        userService.update(user);
        toJSON(resp, Result.ok("更新成功"));
    }

    private void selectById(HttpServletRequest req, HttpServletResponse resp) {
        System.out.println("UserServlet.selectById");
        String id = req.getParameter("id");
        User user = userService.selectById(Integer.parseInt(id));
        toJSON(resp, Result.ok(user));
    }

    private void add(HttpServletRequest req, HttpServletResponse resp) {
        System.out.println("UserServlet.add");
        User user = MyBeanUtils.copyToBean(req, User.class);
        userService.add(user);
        toJSON(resp, Result.ok("添加成功"));
    }

    private void deleteAll(HttpServletRequest req, HttpServletResponse resp) {
        System.out.println("UserServlet.deleteAll");
        String[] ids = req.getParameterValues("ids[]");
        userService.deleteAll(ids);
        toJSON(resp, Result.ok("删除成功"));
    }

    private void deleteById(HttpServletRequest req, HttpServletResponse resp) {
        System.out.println("UserServlet.deleteById");
        String id = req.getParameter("id");
        userService.deleteById(Integer.parseInt(id));
        toJSON(resp, Result.ok("删除成功"));
    }

    private void selectByPage(HttpServletRequest req, HttpServletResponse resp) {
        System.out.println("UserServlet.selectByPage");
        UserQuery userQuery = MyBeanUtils.copyToBean(req, UserQuery.class);
        PageInfo pageInfo = userService.selectByPage(userQuery);

        toJSON(resp, pageInfo);
    }

    private void login(HttpServletRequest req, HttpServletResponse resp) {
        System.out.println("UserServlet.login");
        String name = req.getParameter("name");
        String password = req.getParameter("password");
        String code = req.getParameter("code");

        String regexName = "^[a-zA-Z0-9_\\u4e00-\\u9fa5\\s·]+$";
        Pattern pattern = Pattern.compile(regexName);
        Matcher matcher = pattern.matcher(name);
        if (!matcher.find()) {
            JSONUtils.toJSON(resp, Result.error("用户名不能有特殊字符"));
            return;
        }

        //先判断验证码是不是正确
        //1、验证码错误，返回一个验证码错误的提示
        //2、验证码正确，再验证验证码是不是正确
        HttpSession session = req.getSession();
        String codeInSession = (String) session.getAttribute("codeInSession");
        if (!codeInSession.equalsIgnoreCase(code)) {
            JSONUtils.toJSON(resp, Result.error("验证码错误"));
            return;
        }

        User user = userService.login(name, password);
        /*if (user == null) {
            JSONUtils.toJSON(resp, Result.error("用户名或者密码错误"));
        } else {
            if (user.getStatus() == 0) {
                JSONUtils.toJSON(resp, Result.error("该用户已经禁用，请联系管理员"));
                return;
            }
            session.setAttribute("user", user);
            JSONUtils.toJSON(resp, Result.ok("登录成功"));

        }*/
        if (user == null) {
            JSONUtils.toJSON(resp, Result.error("用户名或者密码错误"));
            return;
        }
        if (user.getStatus() == 0) {
            JSONUtils.toJSON(resp, Result.error("该用户已经禁用，请联系管理员"));
            return;
        }

        //自动登录
        //判断有没有勾选自动登录
        String autoLogin = req.getParameter("autoLogin");
        if (!ObjectUtils.isEmpty(autoLogin)) {
            Cookie cookie = new Cookie("autoLogin", user.getName() + "&" + user.getPassword());
            //设置Cookie 的存活时间和绑定路径
            cookie.setMaxAge(60*60*24*7);//设置时间为1周
            cookie.setPath(req.getContextPath());
            //在响应resp中添加cookie，返回给浏览器
            resp.addCookie(cookie);
        }

        session.setAttribute("user", user);
        List<Auth> auths = authService.selectByRole(user.getRole());
        session.setAttribute("auths", auths);
        JSONUtils.toJSON(resp, Result.ok("登录成功"));
    }

    private void logout(HttpServletRequest req, HttpServletResponse resp) {
        System.out.println("UserController.logout");
        HttpSession session = req.getSession();
        session.removeAttribute("user");
        session.removeAttribute("auths");

        Cookie cookie = CookieUtils.getCookie(req, "autoLogin");
        //如果用户没有勾选自动登录，那么这个Cookie就是null，回报空指针异常，所以要加判断
        if (cookie != null) {
            //设置Cookie的存活时间为0
            cookie.setMaxAge(0);
            resp.addCookie(cookie);
        }

        toJSON(resp, Result.ok("退出成功"));
    }
}